﻿using System;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Xml;

namespace XmlSoccerGrabber {
    class Program {
        static void Main(string[] args) {

            while(true) {
                CaptureLivescores();
                Thread.Sleep(30000);
            }

        }

        private static void CaptureLivescores() {
            var date = DateTime.Now;
            var directory = Path.Combine(ConfigurationManager.AppSettings["livescoreDirectory"], date.ToString("yyyy-MM-dd"));
            if(!Directory.Exists(directory)) {
                Directory.CreateDirectory(directory);
            }
            var file = Path.Combine(directory, string.Format("livescore{0}.xml", date.ToString("yyyyMMddHHmmssfff")));

            try {
                var client = new XmlSoccerService.FootballDataSoapClient();
                
                var response = client.GetLiveScore(ConfigurationManager.AppSettings["xmlSoccerAPIKey"]);
                var document = new XmlDocument();
                document.LoadXml(response.OuterXml);
                document.Save(file);
                Console.WriteLine("Livescore updated at {0}. Filename: {1}", date.ToString("yyyy-MM-dd HH:mm ss"), file);
            }
            catch(Exception) {
                Console.WriteLine("Livescore failed at {0}", date.ToString("yyyy-MM-dd HH:mm ss"));
            }
        }
    }
}
